package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.GiftObject;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.module.excitation.adapter.SelectGiftAdapter;
import com.lishe.lishe.lishe.module.recharge.activity.RechargeIntegralActivity;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/10/24.
 * 赠送小礼
 */

public class SelectGiftActivity extends BaseActivity implements View.OnClickListener {

    private Button callBack;
    private TextView title;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private TextView integral;
    private TextView sendTo;
    private TextView rechargeIntegral;
    private SelectGiftAdapter adapter;
    private LinkedList<GiftObject> images = new LinkedList<>();
    private GiftObject selectGiftObject;//被选中的小礼
    private String commonIntegral;//通用积分

    public static void jump(Activity activity, int requcode) {
        Intent intent = new Intent(activity, SelectGiftActivity.class);
        activity.startActivityForResult(intent, requcode);
    }

    public static void jump(Fragment fragment, int requcode) {
        Intent intent = new Intent(fragment.getActivity(), SelectGiftActivity.class);
        fragment.startActivityForResult(intent, requcode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_gift);
        adapter = new SelectGiftAdapter(this, images, BitmapUtils.getDisplayWidth(this));
        initView();
    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        title = findViewById(R.id.title_text_title);
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshlayout);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
//        recyclerView.addItemDecoration(new RecyclerGriadViewItemDecoration(Utils.dip2px(this,10), 0, 0));
        recyclerView.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(context, 10), 0, Utils.dip2px(context, 10)));
        recyclerView.setAdapter(adapter);
        integral = findViewById(R.id.integral);
        rechargeIntegral = findViewById(R.id.recharge_intagral);
        sendTo = findViewById(R.id.send_to);
        sendTo.setBackgroundColor(getResources().getColor(R.color.color4138));
        rechargeIntegral.setVisibility(View.GONE);
        title.setText("赠送小礼");
        setListener();
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        rechargeIntegral.setOnClickListener(this);
        sendTo.setOnClickListener(this);
//        recyclerView.setOnItemClickListener(new RefreshRecyclerView.ItemClickListener() {
//            @Override
//            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
//                selectGiftObject = images.get(position);
//                if(commonIntegral==null){
//                    toast("未能获取积分信息，请刷新重试！");
//                }else{
//                    if (Integer.valueOf(commonIntegral) < selectGiftObject.getGiftCost()) {
//                        sendTo.setBackgroundColor(getResources().getColor(R.color.gray_9));
//                        rechargeIntegral.setVisibility(View.VISIBLE);
//                    } else {
//                        sendTo.setBackgroundColor(getResources().getColor(R.color.color4138));
//                        rechargeIntegral.setVisibility(View.GONE);
//                    }
//                }
//            }
//        });
//        recyclerView.setOnRefreshListener(new RecyclerViewRefreshListener() {
//            @Override
//            public void onHeaderRefresh(View headerView) {
//                getGift();
//                getIntegral();
//            }
//
//            @Override
//            public void onFooterRefresh(View footerViwe) {
//                recyclerView.setFooterRefreshEnabled(false);
//            }
//        });
//        recyclerView.setRefreshing();
        adapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                selectGiftObject = images.get(position);
                if(commonIntegral==null){
                    toast("未能获取积分信息，请刷新重试！");
                }else{
                    if (Integer.valueOf(commonIntegral) < selectGiftObject.getGiftCost()) {
                        sendTo.setBackgroundColor(getResources().getColor(R.color.gray_9));
                        rechargeIntegral.setVisibility(View.VISIBLE);
                    } else {
                        sendTo.setBackgroundColor(getResources().getColor(R.color.color4138));
                        rechargeIntegral.setVisibility(View.GONE);
                    }
                }
            }
        });
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getGift();
                getIntegral();
            }
        });
        refreshLayout.autoRefresh();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.recharge_intagral://充值积分
                RechargeIntegralActivity.jumpForResult(SelectGiftActivity.this, Globals.REQUSE_CODE_RechargeIntegralActivity);
                break;

            case R.id.send_to://送给Ta
                if (selectGiftObject == null) {
                    toast("请先选择小礼！");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("gift", selectGiftObject);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

    private void getGift() {
        HttpExcitation.searchEncourageGifts(Globals.getToken(), getGiftRespose);
    }

    AsyncHttpResponseHandler getGiftRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
           refreshLayout.finishRefresh();
            String result = new String(responseBody);
            Log.e("获取小礼列表", result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.optInt("result") == 100 && jsonObject.optInt("errcode") == 0) {
                    images.clear();
                    JSONObject data = jsonObject.optJSONObject("data");
                    JSONArray infoArray = data.optJSONArray("info");
                    for (int i = 0; i < infoArray.length(); i++) {
                        JSONObject infoObjiect = infoArray.optJSONObject(i);
                        GiftObject giftObject = new GiftObject();
                        giftObject = JSON.parseObject(infoObjiect.toString(), GiftObject.class);
                        images.add(giftObject);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    toast(jsonObject.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            refreshLayout.finishRefresh();
        }
    };

    /**
     * 过滤没有被选中的imageObject
     */
    private void chioceImage() {
        for (int i = images.size() - 1; i >= 0; i--) {
            GiftObject image = images.get(i);
            if (!image.isSelect()) {
                images.remove(image);
            }
        }
    }

    private void getIntegral() {
        HttpUser.getIntegral(responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            Log.e("积分", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    commonIntegral = data.optString("remainScore");
                    integral.setText(commonIntegral);
                } else {
                    toast(json.optString("msg"));
                }
            } catch (JSONException e) {


            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Globals.REQUSE_CODE_RechargeIntegralActivity) {
            getIntegral();
        }
    }
}
